/**
 * calculator
 *
 * @author : tzy
 * @Date : 2021-03-16
 * @Description:
 **/

package com.tang.calculator.symbols;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;

@Component
public class ValueSymbolFactory {

    static ApplicationContext staticApplicationContext;

    @Autowired
    ApplicationContext applicationContext;

    public static ValueSymbol create(String value) {

        if (value.toLowerCase().equals("true")) {
            return new BigDecimalValueSymbol(BigDecimal.ONE.toString());
        } else if (value.toLowerCase().equals("false")) {
            return new BigDecimalValueSymbol(BigDecimal.ZERO.toString());
        } else if (isNumber(value)) {
            return new BigDecimalValueSymbol(value);
        } else {
            return new ReferenceValueSymbol(staticApplicationContext, value);
        }
    }

    private static boolean isNumber(String value) {
        try {
            new BigDecimal(value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public ValueSymbol createNull() {
        return new NullValueSymbol();
    }

    public static ValueSymbol createString(String value) {
        return new StringValueSymbol(value);
    }

    @PostConstruct
    public void init() {
        staticApplicationContext = applicationContext;
    }
}
